package com.eden.service.Impl;

import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eden.common.Archives;
import com.eden.common.R;
import com.eden.dto.*;
import com.eden.entity.Article;
import com.eden.entity.ArticleBody;
import com.eden.entity.ArticleTag;
import com.eden.entity.SysUser;
import com.eden.mapper.ArticleBodyMapper;
import com.eden.mapper.ArticleMapper;
import com.eden.mapper.ArticleTagMapper;
import com.eden.service.*;
import com.eden.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public R listArticle(PageParams pageParams) {

        //分页查询article
        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //置顶先排序
        queryWrapper.orderByDesc(Article::getWeight);

        queryWrapper.orderByDesc(Article::getCreateDate);
        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords();
        //数据不能直接返回
        List<ArticleDto> articleDaoList = copyList(records,true,true);

        return R.success(articleDaoList);
    }

    @Override
    public R hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId,Article::getTitle);
        //"limit"字待串后要加空格，不要忘记加空格，不然会把数据拼到一起
        queryWrapper.last("limit "+limit);
        //select id,title from article order by view_counts desc limt 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        //返回Dto对象
        return R.success(copyList(articles,false,false));
    }

    @Override
    public R newArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId,Article::getTitle);
        //"limit"字待串后要加空格，不要忘记加空格，不然会把数据拼到一起
        queryWrapper.last("limit "+limit);
        //select id,title from article order by view_counts desc limt 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        //返回Dto对象
        return R.success(copyList(articles,false,false));

    }

    @Override
    public R listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return R.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;
    @Override
    public R findArticleById(Long articleId) {

        //1. 根据id查询 文章信息
        //2. 根据bodyId和categoryid 去做关联查询

        Article article = this.articleMapper.selectById(articleId);
        ArticleDto articleDto = copy(article, true, true,true,true);
        //查看完文章之后，本应该直接返回数据了，这时候做了一个更新操作，更新时加写锁，阻塞其他的读操作，性能就会比较低
        // 更新 增加了此次接口的 耗时 如果一旦更新出问题，不应影响查看文章的操作
        //线程池  可以把更新操作 扔到线程池中去执行，和主线程就不相关了
        threadService.updateArticleViewCount(articleMapper,article);
        return R.success(articleDto);
    }

    @Override
    @Transactional
    public R publish(ArticleParam articleParam) {
        //注意想要拿到数据必须将接口加入拦截器
        SysUser sysUser = UserThreadLocal.get();

        /**
         * 1. 发布文章 目的 构建Article对象
         * 2. 作者id  当前的登录用户
         * 3. 标签  要将标签加入到 关联列表当中
         * 4. body 内容存储 article bodyId
*/        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setCategoryId(articleParam.getCategory().getId());
        article.setCreateDate(System.currentTimeMillis());
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        article.setBodyId(-1L);
        //插入之后 会生成一个文章id（因为新建的文章没有文章id所以要insert一下
        //官网解释："insart后主键会自动'set到实体的ID字段。所以你只需要"getid()就好
//        利用主键自增，mp的insert操作后id值会回到参数对象中
        //https://blog.csdn.net/HSJ0170/article/details/107982866
        this.articleMapper.insert(article);

        //tags
        List<TagDto> tags = articleParam.getTags();
        if (tags != null) {
            for (TagDto tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                articleTag.setTagId(tag.getId());
                this.articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBody.setArticleId(article.getId());
        articleBodyMapper.insert(articleBody);
//插入完之后再给一个id
        article.setBodyId(articleBody.getId());
        //MybatisPlus中的save方法什么时候执行insert，什么时候执行update
        // https://www.cxyzjd.com/article/Horse7/103868144
        //只有当更改数据库时才插入或者更新，一般查询就可以了
        articleMapper.updateById(article);

        ArticleDto articleDto = new ArticleDto();
        articleDto.setId(article.getId());
        return R.success(articleDto);
    }



    private List<ArticleDto> copyList(List<Article> records,boolean isTag,boolean isAuthor) {

        List<ArticleDto> articleDtoList = new ArrayList<>();

        for (Article record : records) {
            articleDtoList.add(copy(record,isTag,isAuthor,false,false));
        }
        return articleDtoList;

    }
    private List<ArticleDto> copyList(List<Article> records, boolean isTag, boolean isAuthor,boolean isBody,boolean isCategory) {
        List<ArticleDto> articleDtoList = new ArrayList<>();
        for (Article record : records) {
            articleDtoList.add(copy(record, isTag, isAuthor, isBody, isCategory));
        }
        return articleDtoList;
    }

    @Autowired
    private CategoryService categoryService;

    private ArticleDto copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory){
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(article, articleDto);
        articleDto.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //并不是所有的接口都需要标签和作者信息
        if(isTag){
            Long articleId = article.getId();
            //后段数据给的是Tages，前端接收的是叫tags，把两个保持一致就有数据了hehe

            articleDto.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            //拿到作者id
            Long authorId = article.getAuthorId();

            articleDto.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            articleDto.setBody(findArtilcleBodyById(bodyId));
        }
        if (isCategory){
            Long categoryId = article.getCategoryId();
            articleDto.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleDto;

    }

    @Autowired
    private ArticleBodyMapper articleBodyMapper;


    private ArticleBodyDto findArtilcleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyDto articleBodyDto =  new ArticleBodyDto();
        articleBodyDto.setContent(articleBody.getContent());
        return articleBodyDto;

    }
}
